package com.example.main;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileUtils {

    public static void splitFile(String filePath,int fileCount) throws IOException {
        FileInputStream fis=new FileInputStream(filePath);
        FileChannel channel = fis.getChannel();
        final long fileSize=channel.size();
        long avg = fileSize / fileCount;
        int bufferSize=200;
        ByteBuffer allocate = ByteBuffer.allocate(bufferSize);
        long startPosition=0;
        long endPosition=avg<bufferSize?0:avg-bufferSize;

        for (int i = 0; i < fileCount; i++) {
            if (i+1 !=fileCount){
                int read=channel.read(allocate,endPosition);
                readW:
                while ((read!=-1)){
                    allocate.flip();
                    byte[] array = allocate.array();
                    for (int j = 0; j < array.length; j++) {
                        byte b=array[j];
                        if (b==10 || b==13){
                            endPosition+=j;
                            break readW;
                        }
                        endPosition+=bufferSize;
                        allocate.clear();
                        read=channel.read(allocate,endPosition);
                    }
                }
            }else {
                endPosition=fileSize;
            }

            FileOutputStream fos=new FileOutputStream(filePath+(i+1));
            FileChannel fosChannel = fos.getChannel();
            channel.transferTo(startPosition,endPosition-startPosition,fosChannel);
            fos.close();
            startPosition=endPosition+1;
            endPosition+=avg;

        }
        channel.close();
        fis.close();
    }
}
